package com.huffman.smart_picture.api.download.pexels;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.huffman.smart_picture.api.download.ObtainImage;
import com.huffman.smart_picture.api.download.ObtainImageQueryDto;
import com.huffman.smart_picture.api.download.ObtainImageResult;
import com.huffman.smart_picture.common.exception.BusinessException;
import com.huffman.smart_picture.common.exception.ErrorEnum;
import com.huffman.smart_picture.domain.enums.PictureCategoryEnum;
import com.huffman.smart_picture.utils.TranslateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author DengLin
 * @title pexels图片获取
 * @date 2025/3/28
 */
@Slf4j
@Component
public class PexelsImageApi implements ObtainImage {

    @Value("${api.download.pexels.secret}")
    private String PEXELS_SECRET;

    private static final String URL = "https://api.pexels.com/v1/search?";

    @Override
    public List<ObtainImageResult> getImageUrls(ObtainImageQueryDto obtainImageQueryDto) {

//        ThrowUtil.throwIf(!(obtainImageQueryDto instanceof PexelsImageQueryDto), ErrorEnum.PARAM_ILLICIT, "pexels 类型请求参数转换异常");
        PexelsImageQueryDto pexelsImageQueryDto = (PexelsImageQueryDto) obtainImageQueryDto;
        List<ObtainImageResult> imageResults = new ArrayList<>();

        // 构建查询url
        String url = buildUrl(pexelsImageQueryDto);

        HashMap<String, String> headers = new HashMap<>();
        headers.put("Authorization", PEXELS_SECRET);
        try {
            HttpResponse httpResponse = HttpUtil.createGet(url.toString())
                    .addHeaders(headers)
                    .execute();

            if (httpResponse.getStatus() != HttpStatus.HTTP_OK) {
                log.info("use pexels api fail,message:{}", httpResponse.getStatus());
                throw new BusinessException(ErrorEnum.SYSTEM_ERROR, "调用pexels接口失败");
            }
            // 返回结果 https://www.pexels.com/zh-cn/api/documentation/#photos-search
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode photosNode = objectMapper.readTree(httpResponse.body()).get("photos");
            for (JsonNode photoNode : photosNode) {
                String imageUrl = photoNode.get("src").get("original").asText();
                String alt = photoNode.get("alt").asText();
                ObtainImageResult imageResult = new ObtainImageResult();
                imageResult.setUrl(imageUrl);
                // 翻译alt内容
                imageResult.setAlt(TranslateUtil.englishToChinese(alt));
                imageResult.setAvgColor("avg_color");
                imageResults.add(imageResult);
            }
        } catch (Exception e) {
            log.error("use pexels api fail,message:{}", e.getStackTrace());
            throw new BusinessException(ErrorEnum.SYSTEM_ERROR, "调用pexels接口失败");
        }
        return imageResults;
    }

    /**
     * 构建查询url
     *
     * @param pexelsImageQueryDto
     * @return
     */
    private String buildUrl(PexelsImageQueryDto pexelsImageQueryDto) {
        PexelsQuerySizeEnum pexelsQuerySizeEnum = pexelsImageQueryDto.getPexelsQuerySizeEnum();
        String color = pexelsImageQueryDto.getColor();
        String searchKey = pexelsImageQueryDto.getSearchKey();
        Integer page = pexelsImageQueryDto.getPage();
        Integer perPage = pexelsImageQueryDto.getPerPage();

        // 校验参数
        if (StrUtil.isBlankIfStr(searchKey)) {
            throw new BusinessException(ErrorEnum.REQUEST_PARAM_EMPTY, "pexels图片获取查询关键词为空");
        }

        if (perPage >= 80) {
            perPage = 80;
        }

        //构建url
        StringBuilder url = new StringBuilder(URL);
        url.append("query=" + searchKey)
                .append("&size=" + pexelsQuerySizeEnum.getSize());
        if (!StrUtil.isBlankIfStr(color)) {
            url.append("&color=" + color);
        }

        url.append("&page=" + page)
                .append("&per_page=" + perPage);
        return url.toString();
    }

    public static void main(String[] args) {
        PexelsImageApi pexelsImagesApi = new PexelsImageApi();
        PexelsImageQueryDto pexelsImageQueryDto = new PexelsImageQueryDto();
        pexelsImageQueryDto.setSearchKey(PictureCategoryEnum.ANIMAL_WORLD.getEnglish());
        List<ObtainImageResult> imageUrls = pexelsImagesApi.getImageUrls(pexelsImageQueryDto);
        for (ObtainImageResult imageUrl : imageUrls) {
            System.out.println(imageUrl);
        }
    }
}
